package com.example.demo.controller;

import com.example.demo.entity.Order;
import com.example.demo.entity.ParkingLot;
import com.example.demo.entity.PricingStandard;
import com.example.demo.entity.Vehicle;
import com.example.demo.service.OrderServer;
import com.example.demo.service.ParkingLotService;
import com.example.demo.service.PricingStandardService;
import com.example.demo.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
//自动识别跳转路径
@RequestMapping("/order")
public class OrderController {
    private final OrderServer service;
    private final ParkingLotService parkingLotService;
    private final PricingStandardService pricingStandardService;
    private final VehicleService vehicleService;
    @Autowired
    public OrderController(OrderServer service,ParkingLotService parkingLotService,PricingStandardService pricingStandardService,VehicleService vehicleService){
        this.service=service;
        this.parkingLotService=parkingLotService;
        this.pricingStandardService=pricingStandardService;
        this.vehicleService=vehicleService;
    }

    @RequestMapping("/list")//和HTML文件对标
    public String list(Model model){
        //通过model传值到页面
        List<Order> entities=service.getAll();
        model.addAttribute("list",entities);//model打包成list属性完成List对象的值传递
        return "/order/list";
    }


    @RequestMapping(value = "/insert")
    public String insert(Model model){
        // 车辆信息
        List<Vehicle> vehicle = vehicleService.getAll()
                .stream().filter(Vehicle::isActive).toList();
        model.addAttribute("vehicle",vehicle);
        // 所有停车场车信息
        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);
        //新建一个order对象
        model.addAttribute("order",new Order());
        return "/order/edit";
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(
            @ModelAttribute("order") Order entity
            , @RequestParam("isPayComplete") boolean isPayComplete //是否缴费完成
            , @RequestParam("isRequireInvoicing") boolean isRequireInvoicing //是否开发票
            , @RequestParam("parkingLotId") long parkingLotId //停车场ID
            //车辆信息ID
            , @RequestParam("vehicleId") long vehicleId ) throws Exception {

        entity.setPayComplete(isPayComplete);
        entity.setRequireInvoicing(isRequireInvoicing);

        ParkingLot parkingLot=parkingLotService.getById(parkingLotId);
        PricingStandard pricingStandard=pricingStandardService.getById(parkingLot.getPricingStandard().getId());
        Vehicle vehicle=vehicleService.getById(vehicleId);

        entity.setParkingLot(parkingLot);
        entity.setPricingStandard(pricingStandard);
        entity.setVehicle(vehicle);

        Optional.ofNullable(entity.getId())
                .orElse(entity.getId()==null?service.insert(entity):null);

        Optional.ofNullable(entity.getId())
                .ifPresent(order->{
                    Order od=service.getById(entity.getId());
                    od.setOutDateTime(new Date());

                    LocalDateTime in=LocalDateTime.ofInstant(od.getInDateTime().toInstant(), ZoneId.systemDefault());
                    LocalDateTime out=LocalDateTime.ofInstant(od.getOutDateTime().toInstant(), ZoneId.systemDefault());
                    Long durationHour= Duration.between(in,out).toHours();//停车时间

                    od.setPayComplete(isPayComplete);
                    od.setRequireInvoicing(isRequireInvoicing);
                    od.setParkingLot(parkingLot);
                    od.setPricingStandard(pricingStandard);
                    od.setVehicle(vehicle);

                    if(durationHour<24 && durationHour<od.getPricingStandard().getExceedingHours()){
                        od.setPrice(BigDecimal.valueOf(od.getPricingStandard().getHourlyRate()*durationHour));
                    }else {
                        Long durationDay=durationHour/24;
                        durationHour=durationHour%24;
                        od.setPrice((BigDecimal.valueOf(od.getPricingStandard().getDailyRate()*durationDay+
                                od.getPricingStandard().getHourlyRate()*durationHour)));
                    }
                    service.update(od);
                });
        return "redirect:/order/list";
    }



    @RequestMapping(value = "/edit/{id}")
    public String entity(@PathVariable("id") Long id, Model model){
        // 车辆信息，未离场的车辆
        List<Vehicle> vehicle = vehicleService.getAll()
                .stream().filter(Vehicle::isActive).toList();
        model.addAttribute("vehicle",vehicle);

        Order entity=service.getById(id);
        model.addAttribute("order",entity);

        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);

        return "/order/edit";
    }

    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id")Long id,Model model){
        Order entity=service.getById(id);
        model.addAttribute("order",entity);
        return "/order/detail";
    }


    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id")Long id){
        boolean entity=service.delete(id);
        return "redirect:/order/list";
    }

}
